package com.example.zz.example.java;

import android.text.TextUtils;


import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

/**
 * @author JxLiang
 * @email jxliang@iflytek.com
 * @date 2022/3/2 5:15 上午
 * @description FileMD5Utils
 */
public class FileMD5Utils {
    private static final String kTAG = "FileMD5Utils";
    private static final char[] DIGITS_LOWER = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static void checkSum(String filePath, final ICheckSumListener listener) {

//        if (TextUtils.isEmpty(filePath)) {
//            if (listener != null) {
//                listener.onCheckFinish(null);
//            }
//            return;
//        }
//
//        final File file = new File(filePath);
//        if (!file.exists()) {
//            if (listener != null) {
//                listener.onCheckFinish(null);
//            }
//            return;
//        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                FileInputStream fileInputStream = null;
                String md5 = null;
                try {
                    fileInputStream = new FileInputStream(filePath);
                    byte[] buffer = new byte[1024 * 1024];  // 1MB缓冲
                    int result;
                    MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                    while ((result = fileInputStream.read(buffer)) != -1) {
                        messageDigest.update(buffer, 0, result);
                    }
                    byte[] digest = messageDigest.digest();
                    md5 = new String(encodeHex(digest, DIGITS_LOWER));
                } catch (Exception e) {
                } finally {
                    if (fileInputStream != null) {
                        try {
                            fileInputStream.close();
                        } catch (Exception e) {
                        }
                    }
                    final String finalMd = md5;
                    if (listener != null) {
                        listener.onCheckFinish(finalMd);
                    }
                }
            }
        }).start();
    }

    protected static char[] encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << 1];
        int i = 0;

        for (int var5 = 0; i < l; ++i) {
            out[var5++] = toDigits[(240 & data[i]) >>> 4];
            out[var5++] = toDigits[15 & data[i]];
        }

        return out;
    }

    public interface ICheckSumListener {
        void onCheckFinish(String checkSum);
    }
}
